<script lang="ts">
  import { download_file, type FsProgressEvent } from "$lib/api/fs";
  import { get_user_session } from "$lib/api/user";
  import { Channel } from "@tauri-apps/api/core";
  import { readFile } from "@tauri-apps/plugin-fs";

  interface ComponentProps {
    src?: string;
    alt?: string;
    sizeClass?: string;
    borderClass?: string;
    onclick?: () => void;
  }

  let props: ComponentProps = $props();

  let imageSrc = $state(null as null | string);

  function convertToB64(data: Uint8Array): string {
    const chunk = 8 * 1024;
    const dataStrList = [] as string[];
    for (let i = 0; i < data.length / chunk; i++) {
      const buf = data.slice(i * chunk, (i + 1) * chunk);
      dataStrList.push(String.fromCharCode(...buf));
    }
    return btoa(dataStrList.join(""));
  }

  async function adjustImageSrc(srcValue: string) {
    if (srcValue.startsWith("fs:")) {
      const parts = srcValue.substring(3).split("/");
      if (parts.length != 2) {
        return;
      }
      const fsId = parts[0];
      const fileId = parts[1];
      const onEvent = new Channel<FsProgressEvent>();


      const sessionId = await get_user_session();
      const res = await download_file(sessionId, fsId, fileId, "", onEvent);

      if (res.exist_in_local) {
        const data = await readFile(res.local_path);
        imageSrc = `data:image/*;base64,${convertToB64(data)}`;
      }
    } else {
      imageSrc = srcValue;
    }
  }

  $effect(() => {
    adjustImageSrc(
      props.src == "" || props.src == undefined ? "/favicon.png" : props.src,
    );
  });
</script>

{#snippet img()}
  {#if imageSrc != null}
    <img
      alt={props.alt ?? "image"}
      src={imageSrc}
      class={`${props.sizeClass ?? ""} ${props.borderClass ?? ""}`}
    />
  {/if}
{/snippet}

{#if props.onclick != undefined}
  <button
    type="button"
    class="p-0"
    onclick={() => {
      if (props.onclick != undefined) {
        props.onclick();
      }
    }}
  >
    {@render img()}
  </button>
{:else}
  {@render img()}
{/if}
